# -*- coding: utf-8 -*-
import json
import logging

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.generic import TemplateView

from common.notification import db as db
from common.notification.db import upsert_in_app_announcement
from common.utils.api import token_required, check_params
from common.utils.decorator import response_wrapper
from common.utils.tz import utc_to_local_str
from common.notification.model import PUSH_DEVICE, CREATED_BY_TYPE
from common.third.push_notification import push_to_all_android, push_to_all_ios

_LOGGER = logging.getLogger(__name__)


class NotificationView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        created_by = (query_dct.get('created_by') and int(query_dct.get('created_by'))) or False
        if 'notify_type' in query_dct:
            items, total_count = db.list_notification(query_dct, created_by=created_by)
        else:
            items, total_count = db.list_notification(query_dct, True, created_by=created_by)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in 'content', 'extend':
                data[k] = json.loads(data[k] or '{}')
            for k in 'updated_at', 'created_at':
                data[k] = utc_to_local_str(data[k])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        param_dct = json.loads(smart_unicode(req.body))
        check_params(param_dct, ['content', 'expire_ts', 'status'], {'extend': None})

        user_ids = param_dct.get('user_ids') and list(set(param_dct.get('user_ids')))
        db.generate_sys_notification(
            param_dct['content'],
            param_dct['notify_type'],
            param_dct.get('command'),
            status=param_dct['status'],
            extend=param_dct['extend'],
            expire_ts=param_dct.get('expire_ts'),
            user_ids=user_ids,
            created_by=CREATED_BY_TYPE.CONSOLE,
        )
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(NotificationView, self).dispatch(*args, **kwargs)


class SingleNotificationView(TemplateView):
    def get(self, req, notify_id):
        notify_id = long(notify_id)
        item = db.get_notify_by_id(notify_id)
        data = item.as_dict()
        for k in 'content', 'extend':
            data[k] = json.loads(data[k] or '{}')
        for k in 'updated_at', 'created_at':
            data[k] = utc_to_local_str(data[k])
        return data

    def put(self, req, notify_id):
        notify_id = long(notify_id)
        param_dct = json.loads(smart_unicode(req.body))

        db.update_notification(notify_id, param_dct)
        return {}

    def delete(self, req, notify_id):
        notify_id = long(notify_id)
        db.delete_notification(notify_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleNotificationView, self).dispatch(*args, **kwargs)


class XingeNotificationView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        items, total_count = db.list_xinge_notification(query_dct)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in 'updated_at', 'created_at':
                data[k] = utc_to_local_str(data[k])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        param_dct = json.loads(smart_unicode(req.body))
        check_params(param_dct, ['title', 'content'])
        db.upsert_xinge_notification(param_dct)
        # 发送给信鸽
        title = param_dct['title'].encode('utf-8')
        content = param_dct['content'].encode('utf-8')
        send_time = param_dct['send_time'].encode('utf-8')
        command = param_dct['cmd'].encode('utf-8')
        push_device = param_dct['push_device']
        payload = {'send_time': send_time, 'title': title, 'content': content, 'command': command}
        if push_device == PUSH_DEVICE.ALL:
            push_to_all_android(payload)
            push_to_all_ios(payload)
        if push_device == PUSH_DEVICE.ANDROID:
            push_to_all_android(payload)
        if push_device == PUSH_DEVICE.IOS:
            push_to_all_ios(payload)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(XingeNotificationView, self).dispatch(*args, **kwargs)


class SingleXingeNotificationView(TemplateView):
    def get(self, req, notify_id):
        notify_id = long(notify_id)
        item = db.get_xinge_notification(notify_id)
        data = item.as_dict()
        for k in 'updated_at', 'created_at':
            data[k] = utc_to_local_str(data[k])
        return data

    def put(self, req, notify_id):
        notify_id = long(notify_id)
        param_dct = json.loads(smart_unicode(req.body))

        db.upsert_xinge_notification(param_dct, notify_id)
        return {}

    def delete(self, req, notify_id):
        notify_id = long(notify_id)
        db.delete_xinge_notification(notify_id)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleXingeNotificationView, self).dispatch(*args, **kwargs)


class InAppAnnouncementView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        items, total_count = db.list_in_app_announcement(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in 'updated_at', 'created_at':
                data[k] = utc_to_local_str(data[k])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        param_dct = json.loads(req.body)
        upsert_in_app_announcement(param_dct)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(InAppAnnouncementView, self).dispatch(*args, **kwargs)


class SingleInAppAnnouncementView(TemplateView):
    def get(self, req, in_app_announcement_id):
        item = db.get_in_app_announcement(in_app_announcement_id)
        data = item.as_dict()
        for k in 'updated_at', 'created_at':
            data[k] = utc_to_local_str(data[k])
        return data

    def put(self, req, in_app_announcement_id):
        query_dct = json.loads(smart_unicode(req.body))

        db.upsert_in_app_announcement(query_dct, int(in_app_announcement_id))
        return {}

    def delete(self, req, in_app_announcement_id):
        db.delete_in_app_announcement(int(in_app_announcement_id))
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleInAppAnnouncementView, self).dispatch(*args, **kwargs)
